package com.snow.controller.admin;

import com.snow.controller.BaseController;
import com.snow.pojo.model.OptionsDomain;
import com.snow.service.log.LogService;
import com.snow.service.options.OptionsService;
import com.snow.utils.ApiResponse;
import com.snow.utils.Commons;
import com.snow.utils.GsonUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description:
 * @author: snow
 * @Date: 2020-01-31
 **/
@Api("系统设置")
@Controller
@RequestMapping("admin/setting")
public class SettingController extends BaseController {
    private static Logger logger = LoggerFactory.getLogger(SettingController.class);
    @Autowired
    private OptionsService optionsService;
    @Autowired
    private Commons commons;

    @Autowired
    private LogService logService;
    @GetMapping("")
    public String toSetting(Model model){
        List<OptionsDomain> optionsList = optionsService.getAllOptions();
        HashMap<String, String> options = new HashMap<>();
        optionsList.forEach(option->{
            options.put(option.getName(),option.getValue());
        });
        model.addAttribute("options",options);
        model.addAttribute("commons",commons);
        return "admin/setting";
    }
    @ApiOperation("保存设置")
    @PostMapping("")
    @ResponseBody
    public ApiResponse save(HttpServletRequest request){

        try{
            Map<String, String[]> parameterMap = request.getParameterMap();
            HashMap<String, String> options = new HashMap<>();
            parameterMap.forEach((key,value)->{
                options.put(key,join(value));
            });
            optionsService.saveOption(options);
            logService.addLog("保存设置", GsonUtils.toJsonString(options),request.getRemoteAddr(),null);

        }catch (Exception e){
            e.printStackTrace();
            return ApiResponse.fail("保存失败！");
        }
        return ApiResponse.success();
    }


}
